import 'package:example/edited_data_controller.dart';
import 'package:example/utils/collection_utils.dart';
import 'package:example/video_editor/video_editor_view_model.dart';
import 'package:example/video_editor/view_model_extension.dart';
import 'package:example/video_player/video_player_view_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:jui/jui.dart';
import 'package:zz_video_maker/zz_video_maker.dart';

class VideoEditorToolBar extends StatefulWidget {
  const VideoEditorToolBar({super.key});

  @override
  State<VideoEditorToolBar> createState() => _VideoEditorToolBarState();
}

class _VideoEditorToolBarState extends State<VideoEditorToolBar> {
  VideoEditorViewModel viewModel = Get.find<VideoEditorViewModel>();
  @override
  Widget build(BuildContext context) {
    var list = [
      JUIButton(
        title: '改变比例',
        onPressed: () {
          switch (viewModel.aspectRatio.value) {
            case ERatio.ratio11:
              viewModel.aspectRatio.value = ERatio.ratio169;
              break;
            case ERatio.ratio169:
              viewModel.aspectRatio.value = ERatio.ratio916;
              break;
            default:
              viewModel.aspectRatio.value = ERatio.ratio11;
          }
        },
      ),
      JUIButton(
        title: '添加视频',
        onPressed: () async {
          final rawFile = await ImagePicker().pickMedia();

          // Go to the save video page
          if (rawFile != null) {
            var mediaData = await fileInfo(
              rawFile.path,
            );
            if (mediaData != null) {
              var editData = EditedMedia(mediaData);
              editData.duration = mediaData.duration ?? 0;
              viewModel.allEditedData?.editedMediaList.add(editData);
              await viewModel.initializeDataComplete();
            }
          }
        },
      ),
      JUIButton(
        title: '替换视频',
        onPressed: () async {
          final rawFile = await ImagePicker().pickMedia();

          // Go to the save video page
          if (rawFile != null) {
            var mediaData = await fileInfo(
              rawFile.path,
            );
            if (mediaData != null) {
              viewModel
                  .allEditedData
                  ?.editedMediaList[viewModel.currentIndex.value]
                  .mediaData = mediaData;
              await viewModel.initializeDataComplete();
            }
          }
        },
      ),
      JUIButton(
        title: '删除视频',
        onPressed: () async {
          viewModel.allEditedData?.editedMediaList
              .removeAt(viewModel.currentIndex.value);
          await viewModel.initializeDataComplete();
        },
      ),
      JUIButton(
        title: '贴纸',
        onPressed: () async {
          sticker();
        },
      ),
      JUIButton(
        title: '转场动画',
        onPressed: () {
          viewModel.transition(context);
        },
      ),
      JUIButton(
        title: 'Frames',
        onPressed: () {
          frames();
        },
      ),
      JUIButton(
        title: '文字',
        onPressed: () {
          text();
        },
      ),
    ];

    return Container(
      color: Colors.white,
      child: GridView(
        scrollDirection: Axis.horizontal,
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2, childAspectRatio: 0.25),
        children: list,
      ),
    );
  }

  void sticker() {
    var list = ResourceManager.getInstance().getStickerFetchModels();
    var page = GridView(
      gridDelegate:
          const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4),
      children: list.map((e) {
        return JUIButton(
          title: e.name.toString(),
          onPressed: () {
            var stickerModel = e;
            var current = viewModel.currentEditedMedia;
            if (current == null) {
              return;
            }

            var sticker = EditedStickerData(StickerData.fromFetchModel(
                current.mediaData.key, stickerModel));
            sticker.width = stickerModel.width;
            sticker.height = stickerModel.height;
            sticker.key = stickerModel.name;
            if (sticker.fileInfo != null) {
              extractGifThumbnailPathBy(sticker.fileInfo!).then((value) {
                sticker.fileInfo?.source.path = value;
                current.stickers.add(sticker);
                viewModel.updateSticker();
              });
            }
          },
        );
      }).toList(),
    );
    JUIBottomSheet.showPageContent(
        expand: false,
        barrierColor: Colors.transparent,
        context: context,
        contentBuilder: (context) {
          return Container(
              height: 400, padding: const EdgeInsets.all(16), child: page);
        });
  }

  void text() {
    var list = ResourceManager.getInstance().getTextDataList();
    var page = GridView(
      gridDelegate:
          const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4),
      children: list.map((e) {
        return JUIButton(
          title: e.key.toString(),
          onPressed: () {},
        );
      }).toList(),
    );
    JUIBottomSheet.showPageContent(
        expand: false,
        barrierColor: Colors.transparent,
        context: context,
        contentBuilder: (context) {
          return Container(
              height: 400, padding: const EdgeInsets.all(16), child: page);
        });
  }

  void frames() {
    var values = EMediaLabel.values;

    var page = JUITabBarScrollView(
      titles: values.map((e) {
        return e.toString().split('.').last;
      }).toList(),
      isScrollable: true,
      labelColor: Theme.of(context).primaryColor,
      bodyWidgetBuilder: (context, index) {
        var list = ResourceManager.getInstance().getAllFrames(values[index]);
        return GetBuilder<VideoEditorViewModel>(
          id: 'frame',
          builder: (_) {
            return GridView(
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4),
              children: [
                    JUIButton(
                      onPressed: () {
                        viewModel.currentEditedMedia?.frame = null;
                        viewModel.update(['frame']);
                      },
                      child: Text(
                        '无',
                        style: TextStyle(
                            color: viewModel.currentEditedMedia?.frame == null
                                ? Colors.red
                                : Theme.of(context).primaryColor),
                      ),
                    )
                  ] +
                  list.map((e) {
                    var isSelected =
                        viewModel.currentEditedMedia?.frame?.key == e.key;
                    return JUIButton(
                      onPressed: () async {
                        var fileInfo = e.fileMap[viewModel.aspectRatio.value];
                        if (fileInfo != null) {
                          await extractGifThumbnailPathBy(fileInfo)
                              .then((value) {
                            viewModel.currentEditedMedia?.frame = e;
                            fileInfo.source.path = value;
                            viewModel.updateFrame();
                          });
                        }
                      },
                      child: Text(
                        e.key,
                        style: TextStyle(
                            color: isSelected
                                ? Colors.red
                                : Theme.of(context).primaryColor),
                      ),
                    );
                  }).toList(),
            );
          },
        );
      },
    );

    JUIBottomSheet.showPageContent(
        expand: false,
        barrierColor: Colors.transparent,
        context: context,
        contentBuilder: (context) {
          return Container(
              height: 400, padding: const EdgeInsets.all(16), child: page);
        });
  }
}
